<!-- 退料检验单详情页面 -->
<template>
  <div class="app-container">
    <!-- 返回按钮 -->
    <el-page-header @back="goBack" :content="title" />

    <!-- 基本信息卡片 -->
    <el-card class="box-card" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span>基本信息</span>
      </div>
      <el-descriptions :column="3" border size="medium" v-loading="loading">
        <el-descriptions-item label="检验单编号">{{ rqcInfo.rqcCode }}</el-descriptions-item>
        <el-descriptions-item label="检验单名称">{{ rqcInfo.rqcName }}</el-descriptions-item>
        <el-descriptions-item label="检验类型">
          <el-tag type="warning" v-if="rqcInfo.rqcType === '4'">退料检验</el-tag>
          <span v-else>{{ formatRqcType(rqcInfo.rqcType) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="来源单据编号">{{ rqcInfo.sourceDocCode }}</el-descriptions-item>
        <el-descriptions-item label="来源单据类型">
          <el-tag type="success" v-if="rqcInfo.sourceDocType === '1'">退料单</el-tag>
          <span v-else>{{ rqcInfo.sourceDocType }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="物料编码">{{ rqcInfo.materialCode }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ rqcInfo.materialName }}</el-descriptions-item>
        <el-descriptions-item label="物料规格型号">
          {{ rqcInfo.materialSpec || rqcInfo.materialSfn }}
        </el-descriptions-item>
        <el-descriptions-item label="单位">{{ rqcInfo.unit }}</el-descriptions-item>
        <el-descriptions-item label="检测数量">
          {{ rqcInfo.checkQty || rqcInfo.quantityCheckNum }}
        </el-descriptions-item>
        <el-descriptions-item label="不合格数量">
          {{ rqcInfo.unqualifiedQty || rqcInfo.quantityUnqualifiedNum }}
        </el-descriptions-item>
        <el-descriptions-item label="合格数量">
          {{ rqcInfo.qualifiedQty || rqcInfo.quantityQualifiedNum }}
        </el-descriptions-item>
        <el-descriptions-item label="检测结果">
          <el-tag type="success" v-if="rqcInfo.checkResult === '1'">合格</el-tag>
          <el-tag type="danger" v-else-if="rqcInfo.checkResult === '2'">不合格</el-tag>
          <el-tag type="info" v-else-if="rqcInfo.checkResult === '3'">待检</el-tag>
          <span v-else>{{ rqcInfo.checkResult }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="检验日期">{{ parseTime(rqcInfo.inspectDate) }}</el-descriptions-item>
        <el-descriptions-item label="单据状态">
          <el-tag v-if="rqcInfo.status === '1'">草稿</el-tag>
          <el-tag type="warning" v-else-if="rqcInfo.status === '2'">已提交</el-tag>
          <el-tag type="success" v-else-if="rqcInfo.status === '3'">已审核</el-tag>
          <span v-else>{{ rqcInfo.status }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ rqcInfo.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(rqcInfo.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ rqcInfo.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 检验明细卡片 -->
    <el-card class="box-card" style="margin-top: 15px;">
      <div slot="header" class="clearfix">
        <span>检验明细</span>
      </div>
      <el-table
        v-loading="lineLoading"
        :data="lineList"
        style="width: 100%"
        border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="检测项编码" align="center" prop="indexCode" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="检测项名称" align="center" prop="indexName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="检测项类型" align="center" prop="indexType" min-width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.indexType === '1'" type="info">外观</el-tag>
            <el-tag v-else-if="scope.row.indexType === '2'" type="success">视觉</el-tag>
            <el-tag v-else-if="scope.row.indexType === '3'" type="warning">尺寸</el-tag>
            <el-tag v-else-if="scope.row.indexType === '4'" type="primary">物理性能检测</el-tag>
            <el-tag v-else-if="scope.row.indexType === '5'" type="danger">化学成分检测</el-tag>
            <span v-else>{{ scope.row.indexType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标准值" align="center" prop="standerVal" min-width="100" />
        <el-table-column label="检测要求" align="center" prop="checkMethod" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="检测工具" align="center" prop="qcTool" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="误差上限" align="center" prop="thresholdMax" min-width="80" />
        <el-table-column label="误差下限" align="center" prop="thresholdMin" min-width="80" />
        <el-table-column label="单位" align="center" prop="unit" min-width="80" />
        <el-table-column label="备注" prop="remark" align="center" />
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { getQcRqc, listLine } from "@/api/qc/ReturnInspection";

export default {
  name: "RqcDetail",
  data() {
    return {
      // 标题
      title: "退料检验单详情",
      // 退料检验单ID
      rqcId: null,
      // 退料检验单信息
      rqcInfo: {},
      // 检验明细列表
      lineList: [],
      // 加载状态
      loading: false,
      // 明细加载状态
      lineLoading: false,
      // 请求锁，防止重复提交
      isRequesting: false,
      // 检验类型选项
      rqcTypeOptions: [
        { value: "1", label: "来料检验" },
        { value: "2", label: "出货检验" },
        { value: "3", label: "过程检验" },
        { value: "4", label: "退料检验" }
      ]
    };
  },
  created() {
    // 从路由参数获取退料检验单ID
    const rqcId = this.$route.params.id;
    console.log("路由参数中的ID:", rqcId);
    if (rqcId) {
      this.rqcId = rqcId;
      console.log("设置rqcId:", this.rqcId);
      this.getRqcInfo();
      // 延迟50ms再获取明细，避免和其他生命周期中的请求冲突
      setTimeout(() => {
        if (!this.isRequesting) {
          this.getLineList();
        }
      }, 50);
    } else {
      this.$message.error("未找到退料检验单ID，无法加载详情");
      this.goBack();
    }
  },
  mounted() {
    // 二次确保数据已加载，但不直接调用API，避免重复请求
    if (this.rqcId && !this.lineList.length && !this.isRequesting) {
      console.log("mounted钩子中检测到数据未加载，将重新加载数据");
      // 延迟100ms再获取明细，避免和created中的请求冲突
      setTimeout(() => {
        if (!this.isRequesting && !this.lineList.length) {
          this.getLineList();
        }
      }, 100);
    }
  },
  watch: {
    // 监听路由参数变化
    '$route.params.id': {
      handler(newVal) {
        console.log("路由参数ID变化:", newVal);
        if (newVal && newVal !== this.rqcId) {
          this.rqcId = newVal;
          this.getRqcInfo();
          // 延迟50ms再获取明细，避免和其他监听器中的请求冲突
          setTimeout(() => {
            if (!this.isRequesting) {
              this.getLineList();
            }
          }, 50);
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 返回列表页 */
    goBack() {
      this.$router.push("/qc/ReturnInspection");
    },

    /** 格式化检验类型 */
    formatRqcType(rqcType) {
      const option = this.rqcTypeOptions.find(item => item.value === rqcType);
      return option ? option.label : rqcType;
    },

    /** 获取退料检验单信息 */
    getRqcInfo() {
      this.loading = true;
      getQcRqc(this.rqcId)
        .then(response => {
          this.rqcInfo = response.data || {};
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /** 获取检验明细列表 */
    getLineList() {
      if (!this.rqcId) {
        console.error("无法获取检验明细，rqcId为空");
        return;
      }

      // 防止重复请求
      if (this.isRequesting) {
        console.log("请求正在进行中，跳过重复请求");
        return;
      }

      console.log("开始获取检验明细列表, rqcId:", this.rqcId);
      this.lineLoading = true;
      this.isRequesting = true; // 设置请求锁

      // 确保rqcId是数字类型
      const rqcId = Number(this.rqcId);

      // 构造GET请求的参数对象
      listLine({ rqcId: rqcId })
        .then(response => {
          console.log("检验明细列表响应:", response);
          if (response && response.code === 200) {
            if (response.rows && Array.isArray(response.rows)) {
              this.lineList = response.rows;
              console.log("成功设置检验明细数据(rows):", this.lineList.length, "条记录");
            } else if (response.data && Array.isArray(response.data)) {
              this.lineList = response.data;
              console.log("成功设置检验明细数据(data):", this.lineList.length, "条记录");
            } else {
              console.warn("响应中没有有效的数组数据");
              this.lineList = [];
            }
          } else {
            console.warn("响应状态码异常:", response.code);
            this.lineList = [];
            this.$message.warning(`获取检验明细数据异常: ${response.msg || '未知错误'}`);
          }
          this.lineLoading = false;
          this.isRequesting = false; // 释放请求锁
        })
        .catch(error => {
          console.error("获取检验明细列表失败:", error);
          this.lineList = [];
          this.lineLoading = false;
          this.isRequesting = false; // 确保错误时也释放请求锁
          // 如果是重复提交错误，不显示错误消息给用户
          if (error && error.message && error.message.includes("数据正在处理，请勿重复提交")) {
            console.warn("检测到重复提交，忽略此错误");
          } else {
            this.$message.error("获取检验明细列表失败: " + (error.message || '未知错误'));
          }
        });
    }
  }
};
</script>

<style scoped>
.el-tag {
  padding: 2px 8px;
}
.el-descriptions {
  margin: 10px 0;
}
</style>
